package com.bcqn.controller;

import com.bcqn.common.CommonResponse;
import com.bcqn.model.ForumType;
import com.bcqn.service.ForumTypeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * ForumTypeController
 *
 * @author Kelly
 * @version v1.0
 * @date 2020/4/19 20:56
 */
@RestController
@RequestMapping("/forumType")
public class ForumTypeController {

    @Autowired
    private ForumTypeService forumTypeService;

    /**
     * 管理端：新增圈子类型
     * @param forumType
     * @return
     */
    @PostMapping("/add")
    public CommonResponse add(@RequestBody ForumType forumType) {
        validateForumType(forumType);
        if (forumTypeService.add(forumType) == 1) {
            CommonResponse.success();
        }
        return CommonResponse.fail("新增异常");
    }

    /**
     * 管理端：修改圈子类型
     * @param forumType
     * @return
     */
    @PostMapping("/update")
    public CommonResponse update(@RequestBody ForumType forumType) {
        if (forumType.getId() == null) {
            throw new RuntimeException("参数错误");
        }
        validateForumType(forumType);
        if (forumTypeService.update(forumType) == 1) {
            CommonResponse.success();
        }
        return CommonResponse.fail("更新异常");
    }

    /**
     * 管理端：删除圈子类型
     * @param id
     * @return
     */
    @PostMapping("/delete")
    public CommonResponse delete(@RequestParam Long id, @RequestParam Long userId) {
        // 此为管理端操作，需带着用户token进行，无需校验userId
        if (forumTypeService.delete(id,userId) == 1) {
            CommonResponse.success();
        }
        return CommonResponse.fail("删除异常");
    }

    /**
     * 校验圈子类型参数
     * @param forumType
     */
    private void validateForumType(ForumType forumType) {
        if (StringUtils.isBlank(forumType.getName())) {
            throw new RuntimeException("圈子类型名称不能为空");
        }
        if (forumType.getName().length() > 10) {
            throw new RuntimeException("圈子类型名称超过最大长度");
        }
    }
}
